import { getCampusSelector } from '@/api/campus/campus'
import Divider from '@/components/Generator/index/RightComponents/Divider'
import request from '@/utils/request'
export default {
  components: { Divider },
  props: [],
  data() {
    return {
      loading: false,
      setting: {},
      eventType: '',
      dataForm: {
        id: '',
        brand: undefined,
        campusId: undefined,
        counselor: undefined,
        startDate: undefined,
        endDate: undefined,
        type: undefined,
        teacherCount: 1,
        studentCount: 1,
        summarize: [],
        improve: [],
        checklist: [],
        sparkle: [],
        sparkleMemo: '',
        lack: [],
        lackMemo: '',
        cooperate: [],
        team: [],
        profit: [],
        score: 0,
        pickerDate: [],
        // 提交前承诺声明（必须勾选）
        commitment: true
      },
      cooperate1: 0,
      cooperate2: 0,
      cooperate3: 0,
      cooperate4: 0,
      team1: 0,
      team2: 0,
      team3: 0,
      team4: 0,
      profit1: 0,
      profit2: 0,
      profit3: 0,
      rules: {
        brand: [
          {
            required: true,
            message: '请选择校区品牌',
            trigger: 'change'
          }
        ],
        campusId: [
          {
            required: true,
            message: '请选择校区主键',
            trigger: 'change'
          }
        ],
        counselor: [
          {
            required: true,
            message: '请输入督导师',
            trigger: 'change'
          }
        ],
        pickerDate: [
          {
            required: true,
            message: '请选择督导时间',
            trigger: 'change'
          }
        ],
        type: [
          {
            required: true,
            message: '请输入督导类型',
            trigger: 'change'
          }
        ],
        summarize: [
          {
            required: true,
            message: '请上传督导检核表',
            trigger: 'change'
          }
        ],
        // 承诺声明必须勾选
        commitment: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === true) callback()
              else callback(new Error('请勾选承诺声明后再提交'))
            },
            trigger: 'change'
          }
        ]
      },
      colors: ['#99A9BF', '#F7BA2A', '#FF9900'],
      brandOptions: [],
      campusOptions: [],
      dataItem: {},
      campusLoading: false,
      typeOptions: [{ fullName: '督导巡校', id: '1' }, { fullName: '三好两改', id: '2' }]
    }
  },
  computed: {},
  watch: {
    async 'dataForm.brand'() {
      try {
        this.campusLoading = true
        this.campusOptions = []
        await getCampusSelector({ fields: 'id,fullName', brand: this.dataForm.brand }).then(res => {
          this.campusOptions = Array.isArray(res.data) ? res.data : []
        })
      } catch (error) {
        console.error('加载校区数据失败:', error)
        this.$message.error('校区选项加载失败')
        this.campusOptions = []
      } finally {
        this.campusLoading = false
      }
    },
    'dataForm.campusId': {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.campusOptions.map(o => {
            if (o.id == this.dataForm.campusId) {
              this.dataItem = o
            }
          })
        }
      }
    }
  },
  created() {},
  mounted() {
    this.$store.dispatch('base/getDictionaryData', { sort: 'Brand' }).then(res => {
      this.brandOptions = res
    })
  },
  methods: {
    async handleSubmit() {
      this.$refs.elForm.validate(valid => {
        if (valid) {
          // 额外校验：提交前必须勾选承诺声明
          if (this.dataForm.commitment !== true) {
            this.$message.error('请勾选承诺声明后再提交')
            return false
          }
          console.log('验证通过')
        } else {
          return false
        }
      })
    },
    deleteSparkleItem(key, index) {
      this.dataForm[key].splice(index, 1)
    },
    addSparkleItem(key) {
      this.dataForm[key].push({})
    },
    goBack() {
      this.$emit('refresh')
    },

    templateDownload(name) {
      request({
        url: `/api/campus/supervise/TemplateDownload/${name}`,
        method: 'get'
      }).then(res => {
        console.log(res)
        this.custom.downloadFile(res.data.url)
      })
    },
    init(data) {
      this.setting = data
      this.dataForm.id = data.id || ''
      this.$nextTick(() => {
        this.$refs['elForm'].resetFields()
        if (this.dataForm.id) {
          request({
            url: '/api/campus/supervise/' + this.dataForm.id,
            method: 'get'
          }).then(res => {
            this.dataForm = res.data
            if (!this.dataForm.summarize) this.dataForm.summarize = []
            if (!this.dataForm.improve) this.dataForm.improve = []
            if (!this.dataForm.checklist) this.dataForm.checklist = []
            if (!this.dataForm.sparkle) this.dataForm.sparkle = []
            if (!this.dataForm.lack) this.dataForm.lack = []
            if (this.dataForm.cooperate) {
              this.cooperate1 = this.dataForm.cooperate[0]
              this.cooperate2 = this.dataForm.cooperate[1]
              this.cooperate3 = this.dataForm.cooperate[2]
              if (this.dataForm.cooperate.length == 4) this.cooperate4 = this.dataForm.cooperate[3] ? this.dataForm.cooperate[3] : 0
            }
            if (this.dataForm.team) {
              this.team1 = this.dataForm.team[0]
              this.team2 = this.dataForm.team[1]
              this.team3 = this.dataForm.team[2]
              if (this.dataForm.team.length == 4) this.team4 = this.dataForm.team[3] ? this.dataForm.team[3] : 0
            }
            if (this.dataForm.profit) {
              this.profit1 = this.dataForm.profit[0]
              this.profit2 = this.dataForm.profit[1]
              if (this.dataForm.profit.length == 3) this.profit3 = this.dataForm.profit[2] ? this.dataForm.profit[2] : 0
            }
            if (this.dataForm.startDate && this.dataForm.endDate) {
              this.dataForm.pickerDate = [this.dataForm.startDate, this.dataForm.endDate]
            }
            /*if (this.dataForm.sparkle) {
              this.dataForm.sparkle = JSON.parse(this.dataForm.sparkle)
            }
            if (this.dataForm.lack) {
              this.dataForm.lack = JSON.parse(this.dataForm.lack)
            }*/
          })
        }
      })
    },

    handlePickerDateChange(time) {
      this.dataForm.startDate = time[0]
      this.dataForm.endDate = time[1]
    },
    setCurrentValue() {
      this.dataForm.score = (this.team1 + this.team2 + this.team3 + (this.team4 ? this.team4 : 0) + this.profit1 + this.profit2 + (this.profit3 ? this.profit3 : 0) + this.cooperate1 + this.cooperate2 + this.cooperate3 + (this.cooperate4 ? this.cooperate4 : 0)) * 2 + 10
    },
    dataFormSubmit(eventType) {
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          if (eventType === 'audit' || eventType === 'reject') {
            this.$emit('eventReciver', this.dataForm, eventType)
            return
          }
          this.dataForm.flowState = eventType === 'submit' ? 0 : 1
          this.eventType = eventType
          this.dataForm.cooperate = [this.cooperate1, this.cooperate2, this.cooperate3, this.cooperate4]
          this.dataForm.team = [this.team1, this.team2, this.team3, this.team4]
          this.dataForm.profit = [this.profit1, this.profit2, this.profit3]

          if (this.eventType === 'submit') {
            this.$confirm('您确定要提交当前流程吗, 是否继续?', '提示', {
              type: 'warning'
            }).then(() => {
              this.request()
            })
          } else {
            this.request()
          }
        }
      })
    },
    request() {
      let data = { ...this.dataForm }
      /* if (data.sparkle && data.sparkle.length > 0) {
         data.sparkle = JSON.stringify(data.sparkle)
       }
       if (data.lack && data.lack.length > 0) {
         data.lack = JSON.stringify(data.lack)
       }*/
      this.dataForm.id
        ? request({
            url: `/api/campus/supervise/${this.dataForm.id}`,
            method: 'put',
            data: data
          }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.$emit('close', true)
              }
            })
          })
        : request({
            url: `/api/campus/supervise`,
            method: 'post',
            data: data
          }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.$emit('close', true)
              }
            })
          })
    },
    judgeShow(id) {
      if (!this.setting.formOperates || !this.setting.formOperates.length) return true
      let arr = this.setting.formOperates.filter(o => o.id === id) || []
      if (!arr.length) return true
      let item = arr[0]
      return item.read
    },
    judgeWrite(id) {
      if (!this.setting.formOperates || !this.setting.formOperates.length) return false
      let arr = this.setting.formOperates.filter(o => o.id === id) || []
      if (!arr.length) return true
      let item = arr[0]
      return !item.write
    }
  }
}
